#include <linux/module.h>
#include <linux/init.h>
#include <linux/platform_device.h>

MODULE_LICENSE("GPL");

#define MODULENAME "platformbus" // 与platform_driver的name相同

#define LOG_INFO(fmt, ...) \
    printk(KERN_INFO MODULENAME "device: " fmt, ##__VA_ARGS__)

#define LOG_ERR(fmt, ...) \
    printk(KERN_ERR MODULENAME "device: " fmt, ##__VA_ARGS__)

struct resource res[] = {
    // 这里要根据实际的硬件资源的开发手册进行填写的
    // 我没有硬件资源，这里按着视频写的，无所谓
    [0] = {
        .start = 0x20ac000,
        .end = 0x20ac000 + 0x3,
        .flags = IORESOURCE_MEM, // 资源的类型
        .name = "GPIO5_DR",
    },

};

void platformbus_release(struct device *dev)
{
    LOG_INFO("platformbus_release");
}

struct platform_device dev = {
    .name = MODULENAME, // name of the device, /sys/bus/platform/devices/<name>
    .id = -1,           // 一般写-1，表示不关心id
    .id_auto = true,    // 表示自动分配id
    .resource = res,
    .num_resources = ARRAY_SIZE(res),
    .dev = {
        .release = platformbus_release,
    },
};

static int __init platformbus_init(void)
{
    LOG_INFO("Hello, platformbus\n");

    { // 注册platform_device
        int ret = platform_device_register(&dev);
        if (ret < 0)
        {
            LOG_ERR("platform_device_register failed\n");
            return ret;
        }
        else
        {
            LOG_INFO("platform_device_register success\n");
        }
    }
    return 0;
}

static void platformbus_exit(void)
{

    { // 注销 platform_device
        platform_device_unregister(&dev);
    }

    LOG_INFO("Goodbye, platformbus\n");
}

module_init(platformbus_init);
module_exit(platformbus_exit);
